///////////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2009. Dimarik
//
///////////////////////////////////////////////////////////////////////////////

package
{

import by.blooddy.core.display.resource.LoadableResourceSprite;

import com.bit101.components.CheckBox;
import com.bit101.components.ComboBox;
import com.bit101.components.InputText;
import com.bit101.components.Label;
import com.bit101.components.ProgressBar;
import com.bit101.components.PushButton;

import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.getTimer;

import ru.goodcore.core.GoodCore;
import ru.goodcore.display.GIFLoaderAdv;
import ru.goodcore.utils.ActivityListener;
import ru.goodcore.utils.getDefinitionNames;

/*
import flash.utils.getTimer;
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
*/

/**
 *  @author				Dimarik
 *  @version			1.0
 *  @langversion		3.0
 *  @playerversion		9.0
 * 
 */
[SWF(width="1024", height="768", frameRate="21", backgroundColor="#E0EEEE")]

public class GIFLoaderTest extends GoodCore {

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	public function GIFLoaderTest() {
		super();
		var pattern:uint = 7;
		trace(pattern, ((pattern ^= 1 << 0) & (1 << 0)), pattern);
		trace(pattern, ((pattern ^= 1 << 0) & (1 << 0)), pattern);
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private var _loader:		Loader;

	/**
	 * @private 
	 */
	private var _qname:			QName;

	/**
	 * @private 
	 */
	private var _mc:			MovieClip;

	/**
	 * @private 
	 */
	private var _comboBox:		ComboBox;
	private var _comboBoxIndex:	uint;

	/**
	 * @private 
	 */
	private var _checkBox:		CheckBox;

	/**
	 * @private 
	 */
	private var _inputText:		InputText;

	/**
	 * @private 
	 */
	private var _progressBar:	ProgressBar;

	/**
	 * @private 
	 */
	private var _activity:		ActivityListener;

	/**
	 * @private 
	 */
	private var _label:			Label;

	/**
	 * @private 
	 */
	private var _labelSize:		Label;

	/**
	 * @private 
	 */
	private var _useDelays:		Boolean = true;

	/**
	 * @private 
	 */
	private var _start:			Number;

	/**
	 * @private 
	 */
	private var _data:			ByteArray;

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	protected override function creationComplete():void {
		super.creationComplete();

		super.stage.scaleMode = StageScaleMode.NO_SCALE;
		super.stage.align = StageAlign.TOP_LEFT;

		this._activity = new ActivityListener();
		super.stage.addChild(this._activity);

		super.stage.addEventListener(Event.RESIZE, this.handler_resize);

		var uris:Array = [
			'http://megapont.ru/images/work/42_4.gif',
			'http://i.imgur.com/kzIFl.gif',
			'http://www.ainmarh.com/women.gif',
			'http://www.ntsomz.ru/img/lektro_final20110318.gif',
			'http://www.pixeljoint.com/files/icons/full/gordoculiao.png',
			'http://www.pixeljoint.com/files/icons/nauseating_headache_bunee.gif',
			'http://www.pixeljoint.com/files/icons/full/tree2__r1368268481.gif',
			'http://www.pixeljoint.com/files/icons/megaman_legends_anim.gif',
			'http://www.pixeljoint.com/files/icons/full/tetlunfinished.gif',
			'http://www.pixeljoint.com/files/icons/wherewolf.gif',
			'http://www.pixeljoint.com/files/icons/full/22.gif',
			'http://www.pixeljoint.com/files/icons/full/food.gif',
			'http://gifzona.com/i/mult/05.gif',
			'http://gifzona.com/i/priroda/1111.gif',
			'http://livegif.ru/Gallery/BEST/fox1.gif',
			'http://pimg.dt00.net/pnews/flashki.ru/681770_b.gif',
			'http://www.gas13.ru/v3/pixelart/wall.gif',
			'http://www.gas13.ru/v3/tutorials/11-5.gif',
			'http://www.gas13.ru/v3/tutorials/8-16.gif',
			'http://www.gifandgif.eu/animated_gif/Arrows/Animated%20Gif%20Arrows%20(104).gif',
			'http://www.livegif.ru/Gallery/ZVERI/BIRDS/BIRDHUML.gif',
			'http://www.pixeljoint.com/files/icons/fool.gif',
			'http://www.pixeljoint.com/files/icons/full/4.gif',
			'http://www.pixeljoint.com/files/icons/full/assault_prototype.gif',
			'http://www.pixeljoint.com/files/icons/full/avat.gif',
			'http://www.pixeljoint.com/files/icons/full/dog.gif',
			'http://www.pixeljoint.com/files/icons/full/newmario.gif',
			'http://www.pixeljoint.com/files/icons/full/pcdesign_final.gif',
			'http://www.pixeljoint.com/files/icons/full/shoe.gif',
			'http://www.pixeljoint.com/files/icons/honey_run_arm00.gif',
			'http://www.pixeljoint.com/files/icons/px_spear.gif',
			'http://gifdr.narod.ru/i/dr/03.gif',
			'http://gifdr.narod.ru/i/dr/10.gif',
			'http://www.princeton.edu/~rvdb/JAVA/election2004/TwoMaps.gif',
			'http://www.solarviews.com/raw/jup/ganymed3.gif',
			'http://www.pixeljoint.com/files/icons/full/completed.gif'
		];

		this._checkBox = new CheckBox(super.stage, 500, 35, 'use gif delays', this.handler_delayChange);
		this._checkBox.selected = true;

		this._label = new Label(super.stage, 500, 16, 'Ready');

		this._labelSize = new Label(super.stage, 500, 2, 'Size: hz');

		var progressBar:ProgressBar = new ProgressBar();

		this._progressBar = progressBar;

		var button:PushButton = new PushButton(super.stage, 310, 40, 'Add to list', this.handler_pressButton);
		button.enabled = false;

		button = new PushButton(super.stage, 590, 40, 'Save as..', this.handler_saveButton);

		this._inputText = new InputText(super.stage, 10, 42, 'or type custom URL here...');

		this._inputText.addEventListener(FocusEvent.FOCUS_IN, 
			function(event:Event):void {
				var inp:InputText = InputText(event.currentTarget); 
				inp.removeEventListener(event.type, arguments.callee);
				inp.text = '';
				button.enabled = true;
			}
		);

		this._inputText.width = 290;

		var comboBox:ComboBox = new ComboBox(super.stage, 10, 10, 'choose ULR', uris);

		this._comboBox = comboBox;

		comboBox.width = 400;
		comboBox.addEventListener(Event.SELECT, this.handler_select);

		for (var i:uint = 0; i < uris.length; i++) {
			comboBox.addItem( {label:uris[i]} );
			this._comboBoxIndex++;
		}

		//this._qname = new QName('ru.goodcore', 'GIFMovieClip');
		//this._qname = new QName('', 'CustomMC');

		this.handler_resize(null);
	}

	//-------------------------------------------------------------------------
	//
	//   Events handlers
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private function handler_select(event:Event = null):void {

		if (this._comboBox.selectedItem == null)
			return;

		if (this._mc && this._mc.parent)
			this._mc.parent.removeChild(this._mc);

		this._mc = null;

		System.gc();

		this._label.text = 'Loading...';

		this._comboBox.removeEventListener(Event.SELECT, this.handler_select);

		super.stage.addChild(this._progressBar);

		var uri:String = ComboBox(event.target).selectedItem.label;

		var request:	URLRequest = new URLRequest(uri);

		this._progressBar.value = 0;

		if ( !this._loader ) {
			this._loader = new GIFLoaderAdv(true, this._useDelays, super.stage.frameRate);
			//var loader:Loader = new GIFLoaderAdv(true, this._useDelays, super.stage.frameRate);
			//super.addChild(this._loader);
		}
		
		var loader:Loader = this._loader;

		var li:LoaderInfo = loader.contentLoaderInfo;

		li.addEventListener(Event.INIT,				this.handler_init);
		li.addEventListener(Event.OPEN,				this.handler_open);
		li.addEventListener(Event.COMPLETE,			this.handler_complete);
		li.addEventListener(ProgressEvent.PROGRESS,	this.handler_progress);
		li.addEventListener(IOErrorEvent.IO_ERROR,	this.handler_error);

		var context:	LoaderContext;
		//context = new LoaderContext(false, null, SecurityDomain.currentDomain);
		loader.load(request, context);
	}

	/**
	 * @private
	 */
	private function handler_open(event:Event):void {
		var li:LoaderInfo = event.target as LoaderInfo;
		li.removeEventListener(event.type, arguments.callee);
		this._label.text = 'Open';
		this._labelSize.text = '...';
	}

	/**
	 * @private
	 */
	private function handler_init(event:Event):void {
		var li:LoaderInfo = event.target as LoaderInfo;
		li.removeEventListener(event.type, arguments.callee);
		this._start = getTimer();
	}

	/**
	 * @private
	 */
	private function handler_complete(event:Event):void {
		var li:			LoaderInfo = event.target as LoaderInfo;
		var loader:		Loader = li.loader;
		var content:	DisplayObject = loader.content;

		li.removeEventListener(Event.INIT,				this.handler_init);
		li.removeEventListener(Event.OPEN,				this.handler_open);
		li.removeEventListener(Event.COMPLETE,			this.handler_complete);
		li.removeEventListener(ProgressEvent.PROGRESS,	this.handler_progress);
		li.removeEventListener(IOErrorEvent.IO_ERROR,	this.handler_error);
		
		//trace( getDefinitionNames(li.bytes, true, false) );

		//this._mc = loader.content as MovieClip;

		var sprite:Sprite = new Sprite();
		sprite.addChild(loader.content);

		this._mc = new (loader.content as Object).constructor();
		//var c:Class = li.applicationDomain.getDefinition(this._qname.toString()) as Class;
		//this._mc = new c();

		this.handler_resize(null);

		//this._loader = null;

		super.stage.removeChild(this._progressBar);
		this._comboBox.addEventListener(Event.SELECT, this.handler_select);

		//this._mc.scrollRect = new Rectangle(0, 0, 600, 600);

		this._label.text = 'Done at ' + (getTimer() - this._start) + ' ms';

		super.addChild(this._mc);
	}

	/**
	 * @private
	 */
	private function handler_error(event:Event):void {
		var li:LoaderInfo = event.target as LoaderInfo;
		li.addEventListener(Event.INIT,				this.handler_init);
		li.addEventListener(Event.OPEN,				this.handler_open);
		li.addEventListener(Event.COMPLETE,			this.handler_complete);
		li.addEventListener(ProgressEvent.PROGRESS,	this.handler_progress);
		li.addEventListener(IOErrorEvent.IO_ERROR,	this.handler_error);

		this._label.text = 'Error loading';

		super.stage.removeChild(this._progressBar);

		this._comboBox.removeItem(this._comboBox.selectedItem);
		//this._comboBox.selectedIndex = -1;
		this._comboBox.selectedItem = null;
		this._comboBoxIndex--;

		this._comboBox.addEventListener(Event.SELECT, this.handler_select);
		this._comboBox.dispatchEvent( new Event(Event.SELECT) );
	}

	/**
	 * @private
	 */
	private function handler_progress(event:ProgressEvent):void {
		var li:LoaderInfo = event.target as LoaderInfo;
		this._label.text = 'Loaded ' + li.bytesLoaded + ' bytes';
		this._labelSize.text = 'Size: ' + li.bytesTotal + ' bytes';
		this._progressBar.maximum = li.bytesTotal;
		this._progressBar.value = li.bytesLoaded;
	}



	/**
	 * @private
	 */
	private function handler_delayChange(event:Event):void {
		var checkBox:CheckBox = CheckBox(event.target);
		this._useDelays = checkBox.selected;
		if (this._comboBox.selectedItem)
			this._comboBox.dispatchEvent( new Event(Event.SELECT) );
	}

	/**
	 * @private
	 */
	private function handler_saveButton(event:Event):void {
		var fr:FileReference = new FileReference();
		fr.save(this._data, 'image.swf');
		//fr.browse();
	}

	/**
	 * @private
	 */
	private function handler_pressButton(event:Event):void {
		this._comboBox.removeEventListener(Event.SELECT, this.handler_select);

		if (this._inputText.text == '')
			return;

		var comboBox:	ComboBox = this._comboBox;

		for (var i:uint = 0; i < this._comboBoxIndex; i++) {
			comboBox.selectedIndex = i;
			if (comboBox.selectedItem.label == this._inputText.text)
				return;
		}

		var item:		Object = {label: this._inputText.text};
		comboBox.addItem( item );

		this._comboBoxIndex++;
		comboBox.selectedItem = item;
		comboBox.selectedIndex = this._comboBoxIndex - 1;

		this._comboBox.addEventListener(Event.SELECT, this.handler_select);
		this._comboBox.dispatchEvent( new Event(Event.SELECT) );
	}

	/**
	 * @private
	 */
	private function handler_resize(event:Event):void {
		var displObj:	DisplayObject = this._progressBar;

		if (displObj) {
			displObj.x = (super.stage.stageWidth - displObj.width) >> 1;
			displObj.y = (super.stage.stageHeight - displObj.height) >> 1;
		}

		displObj = this._mc;

		if (displObj) {
			//trace(displObj.width);
			displObj.x = (super.stage.stageWidth - displObj.width) >> 1;
			displObj.y = (super.stage.stageHeight - displObj.height) >> 1;
		}

		this._activity.x = super.stage.stageWidth - this._activity.width - 20;
		this._activity.y = 5;

	}

}
}